package org.changs.aplug.utils;

import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;

/**
 * Created by yincs on 2017/9/13.
 */

public class FragmentUtils {

    public static <T extends Fragment> T newInstance(Class<T> clazz) {
        try {
            return clazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static <T extends Fragment> T addUniqueFragment(AppCompatActivity activity, @IdRes int id, Class<T> clazz) {
        return addUniqueFragment(activity, clazz.getName(), id, clazz);
    }

    @SuppressWarnings("unchecked")
    public static <T extends Fragment> T addUniqueFragment(AppCompatActivity activity, String tag, @IdRes int id, Class<T> clazz) {
        T fragment = (T) activity.getSupportFragmentManager().findFragmentByTag(tag);
        if (fragment == null) {
            fragment = FragmentUtils.newInstance(clazz);
            activity.getSupportFragmentManager().beginTransaction()
                    .add(id, fragment, tag)
                    .commit();
        }
        return fragment;
    }


    @SuppressWarnings("unchecked")
    public static <T extends Fragment> T getUniqueFragment(FragmentManager manager, Class<T> clazz) {
        String tag = clazz.getName();
        T fragment = (T) manager.findFragmentByTag(tag);
        if (fragment == null) {
            fragment = newInstance(clazz);
        }
        return fragment;
    }


}
